package com.frogs.ucenter.v1.service.impl.aop;


import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.frogs.framework.util.PageList;
import com.frogs.framework.util.StringUtil;
import com.frogs.framework.web.HttpRequestInfo;
import com.frogs.system.util.ApiUrlParamEnum;
import com.frogs.system.util.AttentionStateEnum;
import com.frogs.system.util.OpenPlatformEnum;
import com.frogs.system.web.api.entity.FeedsRecordActiveMqEntity;
import com.frogs.system.web.api.response.Response;
import com.frogs.ucenter.dao.UserAttentionInfoDao;
import com.frogs.ucenter.dao.WechatUserBaseInfoDao;
import com.frogs.ucenter.entity.WechatUserBaseInfo;
import com.frogs.ucenter.entity.ext.UserAttentionInfoExt;
import com.frogs.ucenter.util.record.FeedsRecordActiveMqSend;
import com.frogs.ucenter.v1.request.UserAttentionUpdateRequest;
import com.frogs.ucenter.v1.util.ApiConstants;

@Aspect
@Service(ApiConstants.VERSION+"userFeedsAopImpl")
public class UserFeedsAopImpl {

	private static final Logger log = LoggerFactory.getLogger(UserHonorAopImpl.class);
	@Autowired
	private FeedsRecordActiveMqSend feedsRecordActiveMqSend;
	@Autowired
	private UserAttentionInfoDao userAttentionDao;
	@Autowired
	private WechatUserBaseInfoDao wechatUserBaseInfoDao;
	
	/**
	 * 在同意请求关注后，记录动作
	 * @param jp
	 * @param result
	 */
	@AfterReturning(pointcut="execution(* com.frogs.ucenter.v1.controller.UserAttentionController.attentionAdd(..)) || "
			+ "execution(* com.frogs.ucenter.v1.controller.UserAttentionController.attentionUpdate(..))",returning="result")
	public void doAttentionAdd(JoinPoint jp, Response result)
	{
		try {
			Integer code = result.getCode();
			if(1 != code ){
				return;
			}
			HttpServletRequest req  = (HttpServletRequest)jp.getArgs()[0];
			HttpRequestInfo requestInfo = new HttpRequestInfo(req);
			
			int followedUserId = requestInfo.getIntParameter(ApiUrlParamEnum.followedUserId.getParamName());
			int followUserId = requestInfo.getIntParameter(ApiUrlParamEnum.followUserId.getParamName());
			int status = requestInfo.getIntParameter(ApiUrlParamEnum.status.getParamName());
			
			if (status == AttentionStateEnum.ATTENTION_STATUS_AGREED.getId()) {
				String actionRecord = "realName成为家庭成员！";
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("eqWechatApplicationId", OpenPlatformEnum.WECHAT_HDC.getId());
				params.put("eqUserId", followUserId);
				PageList<WechatUserBaseInfo> list = wechatUserBaseInfoDao.selectByMap(params , 1 , 1, false);
				actionRecord = actionRecord.replace("realName", list.get(0).getNickName());
				insertUserFeedsRecord(followedUserId,followUserId,actionRecord);
				
				params.clear();
				params.put("eqWechatApplicationId", OpenPlatformEnum.WECHAT_HDC.getId());
				params.put("eqUserId", followedUserId);
				list = wechatUserBaseInfoDao.selectByMap(params , 1 , 1, false);
				actionRecord = "realName成为家庭成员！";
				actionRecord = actionRecord.replace("realName", list.get(0).getNickName());
				insertUserFeedsRecord(followUserId,followedUserId,actionRecord);
			}
			log.info("UserHonorAopImpl.doAttentionAdd========");
			
		} catch (Exception e) {
			log.error("func[@After] jp[" + jp + "] result[" + result + "] error[" + e.getMessage() + "]", e);
		}
		
	}
	
	

	/**
	 * 记录用户行为
	 * @param userId
	 * @param actionRecord
	 */
	private void insertUserFeedsRecord(int userId,int followUserId,String actionRecord) {
		try {
			log.info("insertUserFeedsRecord方执行。关注记录------------>关注者id："+userId+"，被关注者id："+followUserId); 
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("eqFollowedUserId", userId);
			params.put("eqFollowUserId", followUserId);
			params.put("eqStatus", AttentionStateEnum.ATTENTION_STATUS_AGREED.getId());
			params.put("eqOpenPlatformId", OpenPlatformEnum.WECHAT_HDC.getId());
			List<UserAttentionInfoExt> list = userAttentionDao.selectByMapForAttention(params,0,1000); 
			
			FeedsRecordActiveMqEntity feedsRecordActiveMqEntity = new FeedsRecordActiveMqEntity();
			feedsRecordActiveMqEntity.setFollowedUserId(userId);
			feedsRecordActiveMqEntity.setMessage("");      //点赞接口要改，改后在修改
			feedsRecordActiveMqEntity.setType(0); 
			feedsRecordActiveMqEntity.setFollowUserId(followUserId);
			if (list !=null && list.size() > 0) {
				UserAttentionInfoExt userAttentionInfoExt = list.get(0);
				feedsRecordActiveMqEntity.setFamilyId(userAttentionInfoExt.getFamilyId());
				feedsRecordActiveMqEntity.setActionRecord(actionRecord); 
				log.info("发送到activeMq队列的数据："+JSON.toJSONString(feedsRecordActiveMqEntity));  
				feedsRecordActiveMqSend.sendToQueue(feedsRecordActiveMqEntity);
			}
			
		} catch (Exception e) {
			log.error("func[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						"动作发起用户id："+userId+"动作记录："+actionRecord, e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}
		
	}
	
}
